package com.ai.networking.netty.client;

import java.io.IOException;
import java.net.InetSocketAddress;

import com.ai.entity.comm.SysNetty;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理客户端 ，I/O数据读写处理类
 */
@Slf4j
@ChannelHandler.Sharable
public class BootNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter {

    SysNetty sysNetty;

    public BootNettyChannelInboundHandlerAdapter(SysNetty sysNetty) {
        this.sysNetty = sysNetty;
    }

    /**
     * 从服务端收到新的数据时，这个方法会在收到消息时被调用
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception, IOException {
        if (msg == null) {
            return;
        }
        log.info("channelRead:read msg:" + msg.toString() + ";code = " + sysNetty.getCode());
        BootNettyClientChannel bootNettyClientChannel = BootNettyClientChannelCache.get("clientId:" + ctx.channel().id().toString());
        if (bootNettyClientChannel != null) {
            log.info("to do");
            bootNettyClientChannel.setLast_data(msg.toString());
        }

        //回应服务端
        //ctx.write("I got server message thanks server!");
    }

    /**
     * 从服务端收到新的数据、读取完成时调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws IOException {
        log.info("channelReadComplete");
        ctx.flush();
    }

    /**
     * 当出现 Throwable 对象才会被调用，即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException {
        log.info("exceptionCaught");
        cause.printStackTrace();
        ctx.close();//抛出异常，断开与客户端的连接
    }

    /**
     * 客户端与服务端第一次建立连接时 执行
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException {
        super.channelActive(ctx);
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        log.info(clientIp);
    }

    /**
     * 客户端与服务端 断连时 执行
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException {
        super.channelInactive(ctx);
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = inSocket.getAddress().getHostAddress();
        //断开连接时，必须关闭，否则造成资源浪费
        ctx.close();
        log.info("channelInactive:" + clientIp);

        BootNettyClientChannelCache.channelMapCache.remove(sysNetty.getCode());
    }
}